package com.daomx.house.service.impl;

import com.aliyun.oss.OSS;
import com.daomx.config.OSSconfig;
import com.daomx.constant.OssConstant;
import com.daomx.entity.PicUploadResult;
import com.daomx.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * Created by xiaodao
 * date: 2019/8/14
 */
@Service
public class PicUploadService {

	@Autowired
	private OSS ossClient;
	@Autowired
	private OSSconfig osSconfig;

	public PicUploadResult upload(MultipartFile multipartFile) {
		//图片校验.对后缀名校验
		boolean isLegal = false;
		for (String type : OssConstant.IMAGE_TYPE) {
			if (StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)) {
				isLegal = true;
				break;
			}
		}
		PicUploadResult fileUploadResult = new PicUploadResult();
		if (!isLegal) {
			fileUploadResult.setStatus("error");
			return fileUploadResult;
		}
		// 文件新路径
		String fileName = multipartFile.getOriginalFilename();
		String filePath = FileUtil.getFilePath(fileName);
		// 上传到阿里云
		try {
			//路径
			ossClient.putObject(osSconfig.getBucketName(), filePath, new
				ByteArrayInputStream(multipartFile.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
			//上传失败
			fileUploadResult.setStatus("error");
			return fileUploadResult;
		}

		fileUploadResult.setStatus("done");
		fileUploadResult.setName(osSconfig.getUrlPrifix() + filePath);
		fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
		return fileUploadResult;
	}


}
